<template>
	<div>
		<AplidForm ref="formRef" v-bind="BaseFormConfig" v-model="formModel" @change="handleItemChange" @submit="onSubmit"> </AplidForm>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import { BaseFormConfig } from '../../config'
import { getAreaObj } from '@/utils/util'
import { useCommonStore } from '@/stores/common'
import { ElMessageBox } from 'element-plus'
const { setTempParams } = useCommonStore()

const emit = defineEmits(['refresh', 'back'])
const formModel: any = ref({})
const formRef = ref()
const onSubmit = (form, done) => {
  const dpServiceOrgHonors =
		form.dpServiceOrgHonorList &&
		form.dpServiceOrgHonorList.map((item) => {
			return {
				...item,
				creditCode: form.creditCode,
				code: 3036,
			}
		})

	const areaObj: any = getAreaObj(form.areas,'now')
	const areaNameObj: any = getAreaObj(form.areas_name,'now')
	const regionObj: any = getAreaObj(form.region)
	const regionNameObj: any = getAreaObj(form.region_name)
	const params = {
		...form,
		...areaObj,
		...areaNameObj,
		...regionObj,
		...regionNameObj,
    dpServiceOrgHonorList:undefined,
		areas: undefined,
		areas_name: undefined,
		region: undefined,
		region_name: undefined,
		code: 3035,
    dpServiceOrgHonors:dpServiceOrgHonors
	}

	setTempParams({
		creditCode: params.creditCode,
		organizationName: params.orgHomeName,
	})
	apiMod
		.dpServiceOrgHome_gather(params)
		.then((res) => {
			emit('refresh', res.data)
			done()
		})
		.catch((err) => {
			done()
		})
}
const openTip = () => {
	ElMessageBox.confirm('数据已采集，统一社会信用代码重复?', '提示', {
		confirmButtonText: '退出',
		cancelButtonText: '重新输入',
		type: 'warning',
	})
		.then(() => {
			emit('back')
		})
		.catch(() => {
			formModel.value.creditCode = undefined
		})
}

const handleItemChange = (model, item, e) => {
	// 校验统一社会信用代码是否已存在
	if (item.prop == 'creditCode') {
		if (e !== '') {
			apiMod.dpServiceOrgHome_page({ creditCode: e }).then((res) => {
				const data = res.data
				if (data.records.length > 0) {
					openTip()
				}
			})
		}
	}
}
const onSave = () => {
	formRef.value!.onSubmit()
}
defineExpose({
	onSave,
})
</script>

<style scoped></style>
